package com.okyai.kt.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.okyai.common.annotation.DataScope;
import com.okyai.common.core.domain.entity.SysUser;
import com.okyai.common.core.text.Convert;
import com.okyai.common.utils.DateUtils;
import com.okyai.common.utils.ShiroUtils;
import com.okyai.kt.domain.Record;
import com.okyai.kt.domain.RecordDetail;
import com.okyai.kt.domain.RecordPlan;
import com.okyai.kt.domain.Topic;
import com.okyai.kt.domain.TopicItem;
import com.okyai.kt.domain.TopicPlan;
import com.okyai.kt.domain.vo.TableTdVo;
import com.okyai.kt.domain.vo.TableTrVo;
import com.okyai.kt.mapper.RecordDetailMapper;
import com.okyai.kt.mapper.RecordMapper;
import com.okyai.kt.mapper.RecordPlanMapper;
import com.okyai.kt.mapper.TopicItemMapper;
import com.okyai.kt.mapper.TopicMapper;
import com.okyai.kt.service.IRecordService;

/**
 * 档案Service业务层处理
 * 
 * @author okyai
 * @date 2021-03-20
 */
@Service
public class RecordServiceImpl implements IRecordService 
{
    @Autowired
    private RecordMapper recordMapper;
    
    @Autowired
    private TopicMapper topicMapper;
    
    @Autowired
    private TopicItemMapper topicItemMapper;
    
    @Autowired
    private RecordPlanMapper  recordPlanMapper;
    
    @Autowired
    private RecordDetailMapper  recordDetailMapper;

    /**
     * 查询档案
     * 
     * @param recordId 档案ID
     * @return 档案
     */
    @Override
    public Record selectRecordById(Long recordId)
    {
        return recordMapper.selectRecordById(recordId);
    }

    /**
     * 查询档案列表
     * 
     * @param record 档案
     * @return 档案
     */
    @Override
    @DataScope(deptAlias = "d",userAlias = "t")
    public List<Record> selectRecordList(Record record)
    {
        return recordMapper.selectRecordList(record);
    }

    /**
     * 新增档案
     * 
     * @param record 档案
     * @return 结果
     */
    @Override
    public int insertRecord(Record record)
    {
    	SysUser user = ShiroUtils.getSysUser();
    	
    	record.setCreateTime(DateUtils.getNowDate());
    	record.setUserId(user.getUserId());
    	record.setCreateBy(user.getUserName());
    	record.setDeptId(user.getDeptId());
    	//新增课题
    	int rows = recordMapper.insertRecord(record);
    	//新增课题方案
    	insertRecordDetil(record);
        return rows;
    }
    
    /**
     *  创建课题其他数据
     * @param record
     */
    public void insertRecordDetil(Record record) {
    	Topic topic = topicMapper.selectTopicById(record.getTopId());
    	
    	List<TopicPlan> tpList = topic.getTopicPlanList().stream()
    			.sorted(Comparator.comparing(TopicPlan::getPlanSort)).collect(Collectors.toList());
    	
    	List<RecordDetail> rdList = new ArrayList<>();
    	
    	TopicItem item = new TopicItem();
    	item.setTopicId(topic.getTopicId());
    	List<TopicItem> tiList = topicItemMapper.selectTopicItemList(item);
    	
    	//新增课题明细
    	for(TopicPlan tp:tpList) {
    		RecordPlan rp = new RecordPlan();
    		rp.setRecordId(record.getRecordId());
    		rp.setPlanId(tp.getPlanId());
    		rp.setPlanStatus("0");
    		//todo 以下是计算时间
    		//rp.setEstimatedTime(record.getCheckTime());
    		//rp.setLastTime(lastTime);
    		//rp.setReminderTime(reminderTime);
    		recordPlanMapper.insertRecordPlan(rp);
    		String[] ids = tp.getItems().split(",");
    		for(String id:ids) {
    			RecordDetail rd = new RecordDetail();
    			rd.setRecordId(record.getRecordId());
    			rd.setTopicId(record.getTopId());
    			rd.setTopicPlanId(tp.getPlanId());
    			rd.setRecordPlanId(rp.getRecordPlanId());
    			rd.setTopicItemId(Long.parseLong(id));
    			item = getItem(rd.getTopicItemId(),tiList);
    			rd.setTopicItemName(item.getItemTypeName());
    			rd.setDetailType(item.getItemType());
    			rd.setDetailTypeId(item.getItemTypeId());
    			rd.setDetailStatus("0");
    			rdList.add(rd);
    		}
    	}
    	
    	//批量插入RD
    	if(rdList.size()>0) {
    		recordDetailMapper.batchRecordDetail(rdList);
    	}
    	
    }
    
    private TopicItem getItem(Long itemId,List<TopicItem> list) {
    	for(TopicItem it:list) {
    		if(it.getTopicItemId().equals(itemId)) {
    			return it;
    		}
    	}
    	return new TopicItem();
    }

    /**
     * 修改档案
     * 
     * @param record 档案
     * @return 结果
     */
    @Override
    public int updateRecord(Record record)
    {
        record.setUpdateTime(DateUtils.getNowDate());
        return recordMapper.updateRecord(record);
    }

    /**
     * 删除档案对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteRecordByIds(String ids)
    {
        return recordMapper.deleteRecordByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除档案信息
     * 
     * @param recordId 档案ID
     * @return 结果
     */
    @Override
    public int deleteRecordById(Long recordId)
    {
    	//todo删除附件
    	recordMapper.deleteRecordAnnexIdById(recordId);
    	recordMapper.deleteRecordItemIdById(recordId);
    	recordMapper.deleteRecordPlanIdById(recordId);
        return recordMapper.deleteRecordById(recordId);
    }

	@Override
	public Topic selectRecordItem(Record record) {
		
		Topic topic = topicMapper.selectTopicById(record.getTopId());
		//拼装表头
		List<TableTrVo> trs = new ArrayList<>();
		TableTrVo tr1= new TableTrVo();
		tr1.getTd().add(new TableTdVo("",0,3));
		TableTrVo tr2= new TableTrVo();
		tr2.getTd().add(new TableTdVo("",0,3));
		TableTrVo tr3= new TableTrVo();
		tr3.getTd().add(new TableTdVo("",0,3));
		for(TopicPlan p:topic.getTopicPlanList()) {
			tr1.getTd().add(new TableTdVo(p.getPlanType(),0,0));
			tr2.getTd().add(new TableTdVo(p.getPlanName(),0,0));
			tr3.getTd().add(new TableTdVo(p.getDoDate()+(p.getDoDateType().equals("M")?"月":"年")+"&plusmn;"+p.getErrorDate()+"天执行",0,0));
		}		
		trs.add(tr1);
		trs.add(tr2);
		trs.add(tr3);
		topic.setTr(trs);
    	//获取所有项目
    	TopicItem item = new TopicItem();
    	item.setTopicId(topic.getTopicId());
    	List<TopicItem> itemList = topicItemMapper.selectTopicItemList(item);
    	//获取所有记录明细
    	RecordDetail detail = new RecordDetail();
    	detail.setRecordId(record.getRecordId());
    	List<RecordDetail> detailList = recordDetailMapper.selectRecordDetailList(detail);
    	//拼装明细
    	itemList.stream().forEach(it->{
    		for(TopicPlan pl:topic.getTopicPlanList()) {
    			it.getDetailList().add(getDetail(it.getTopicItemId(),pl.getPlanId(),detailList));
    		}
    	});
    	topic.setTopicItemList(itemList);
		return topic;
	}
    
	private RecordDetail getDetail(Long itemId,Long planId,List<RecordDetail> list) {
		for(RecordDetail d:list) {
			if(d.getTopicItemId().equals(itemId)&&d.getTopicPlanId().equals(planId)) {
				return d;
			}
		}
		return new RecordDetail();
	}
    
}
